/**
 * 监听多次点击事件
 * demo: v-repeatClick.5:500="handler" // 5次点击才触发handler，每两次点击不超过500ms(默认值：300ms)
 */
export default {
  //连续点击五次指令
  inserted: (el, { value, arg, modifiers }) => {
    let COUNT = 5;

    if (Object.keys(modifiers)) {
      // 计算点击次数
      const count = Object.keys(modifiers)?.[0];
      if (/^[0-9]+$/g.test(count)) {
        COUNT = count;
      }
    }

    if (!value || typeof value !== "function") {
      console.warn("quinticClick should received a function as value");
      return;
    }
    el.delay = 300; // 默认间隔300ms
    if (/^[0-9]+$/g.test(arg)) {
      // 只有整数才会生效
      el.delay = parseFloat(arg);
    }

    el.clickCount = 0;
    el.timer = null;
    el.handler = function (e) {
      e.stopPropagation();
      e.preventDefault();
      if (e.clientX > 100 || e.clientY > 100) {
        return;
      }
      el.clickCount++;
      if (el.clickCount >= COUNT) {
        el.clickCount = 0;
        value();
      }
      if (el.timer) {
        clearTimeout(el.timer);
      }
      el.timer = setTimeout(() => {
        el.clickCount = 0;
      }, el.delay);
    };
    el.addEventListener("click", el.handler);
  },
  unbind: (el) => {
    el.clickCount = 0;
    el.removeEventListener("click", el.handler);
    el.timer && clearTimeout(el.timer);
  },
};
